#include "user_manager.hpp"
#include <algorithm>

UserManager user_manager;

void UserManager::add_user(int fd) {
    std::lock_guard<std::mutex> lock(mtx);
    fd_to_name[fd] = "anonymous";
    fds.push_back(fd);
}

void UserManager::remove_user(int fd) {
    std::lock_guard<std::mutex> lock(mtx);
    auto it = fd_to_name.find(fd);
    if (it != fd_to_name.end()) {
        name_to_fd.erase(it->second);
        fd_to_name.erase(it);
    }
    fds.erase(std::remove(fds.begin(), fds.end(), fd), fds.end());
}

void UserManager::rename_user(int fd, const std::string& name) {
    std::lock_guard<std::mutex> lock(mtx);
    auto old_name = fd_to_name[fd];
    name_to_fd.erase(old_name);
    fd_to_name[fd] = name;
    name_to_fd[name] = fd;
}

std::string UserManager::get_name(int fd) {
    std::lock_guard<std::mutex> lock(mtx);
    auto it = fd_to_name.find(fd);
    return it != fd_to_name.end() ? it->second : "anonymous";
}

int UserManager::get_fd_by_name(const std::string& name) {
    std::lock_guard<std::mutex> lock(mtx);
    auto it = name_to_fd.find(name);
    return it != name_to_fd.end() ? it->second : -1;
}

std::vector<int> UserManager::get_all_fds() {
    std::lock_guard<std::mutex> lock(mtx);
    return fds;
}

void UserManager::add_admin(int fd) {
    std::lock_guard<std::mutex> lock(mtx);
    admin_fds.insert(fd);
}

bool UserManager::is_admin(int fd) {
    std::lock_guard<std::mutex> lock(mtx);
    return admin_fds.count(fd) > 0;
}

void UserManager::mute_user(int fd) {
    std::lock_guard<std::mutex> lock(mtx);
    muted_users.insert(fd);
}

void UserManager::unmute_user(int fd) {
    std::lock_guard<std::mutex> lock(mtx);
    muted_users.erase(fd);
}

bool UserManager::is_muted(int fd) {
    std::lock_guard<std::mutex> lock(mtx);
    return muted_users.count(fd);
}

void UserManager::ban_user(const std::string& name) {
    std::lock_guard<std::mutex> lock(mtx);
    banned_names.insert(name);
}

void UserManager::unban_user(const std::string& name) {
    std::lock_guard<std::mutex> lock(mtx);
    banned_names.erase(name);
}

bool UserManager::is_banned(const std::string& name) {
    std::lock_guard<std::mutex> lock(mtx);
    return banned_names.count(name);
}

bool UserManager::is_admin_name(const std::string& name) {
    return name == "tbx";  
}

bool UserManager::name_exists(const std::string& name) {
    std::lock_guard<std::mutex> lock(mtx);
    return name_to_fd.count(name) > 0;
}

